<template>
  <el-card>
    <el-button
      type="primary"
      :icon="Plus"
      @click="showOrUpdateTrademarkDialog({ id: 0, tmName: '', logoUrl: '' })"
      >添加</el-button
    >

    <el-table
      :data="trademarkList"
      v-loading="loading"
      border
      class="trademark-table"
    >
      <el-table-column label="序号" width="80" type="index" align="center" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column label="品牌LOGO">
        <template v-slot="{ row }">
          <el-image :src="row.logoUrl" fit="cover" class="trademark-img" />
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template v-slot="{ row }">
          <el-button
            type="warning"
            :icon="Edit"
            size="small"
            @click="showOrUpdateTrademarkDialog(row)"
          ></el-button>
          <el-button
            type="danger"
            :icon="Delete"
            size="small"
            @click="deleteTrademark(row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- currentPage  当前页
         pageSize 一页多少条
    -->
    <el-pagination
      class="trademark-pagination"
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9, 12]"
      layout=" prev, pager, next, jumper, sizes,total"
      :total="total"
      @size-change="getTrademarkList"
      @current-change="getTrademarkList"
    />

    <el-dialog
      v-model="dialogVisible"
      :title="`${trademarkFormDate.id ? '修改' : '添加'}品牌`"
    >
      <el-form
        label-width="120px"
        ref="trademarkFormRef"
        :model="trademarkFormDate"
        :rules="trademarkFormDateRules"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input
            placeholder="请输入品牌名称"
            v-model="trademarkFormDate.tmName"
          />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <!--  action 上传的服务器地址 
               action="http://gmall-h5-api.atguigu.cn/admin/product/fileUpload"  会有跨域问题 所以走代理服务器，解决跨域

               考虑以后上线问题 请求前缀不能写死
                action="/app-dev/admin/product/fileUpload" 
          -->
          <el-upload
            class="avatar-uploader"
            :action="`${BASE_URL}/admin/product/fileUpload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkFormDate.logoUrl"
              :src="trademarkFormDate.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>

            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件，且不超过50kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addTrademark">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "TrademarkComponent",
};
</script>

<script lang="ts" setup>
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import { ref, onMounted, reactive } from "vue";

import {
  getTrademarkListApi,
  saveTrademarkApi,
  removeTrademarkApi,
  updateTrademarkApi,
} from "@/api/product/trademark";
import type {
  TrademarkListModel,
  TrademarkModel,
} from "@/api/product/model/trademarkModel";

import type { UploadProps, FormInstance, FormRules } from "element-plus";

import { ElMessage, ElMessageBox } from "element-plus";

// 上传图片功能
// 请求前缀
const BASE_URL = import.meta.env.VITE_API_URL;

// 获取品牌列表
const trademarkList = ref<TrademarkListModel>([]);

const loading = ref(true);

const currentPage = ref(1);

const pageSize = ref(3);

const total = ref(1000);

const getTrademarkList = async () => {
  loading.value = true;
  const res = await getTrademarkListApi(currentPage.value, pageSize.value);
  total.value = res.total;
  trademarkList.value = res.records;
  loading.value = false;
};

onMounted(getTrademarkList);

// 表单数据
const trademarkFormDate = reactive({
  id: 0,
  tmName: "",
  logoUrl: "",
});

// 表单验证规则
const trademarkFormDateRules = reactive<FormRules>({
  tmName: [{ required: true, message: "请输入品牌名称", trigger: "blur" }],
  logoUrl: [{ required: true, message: "请上传品牌LOGO" }],
});

// 表单实例
const trademarkFormRef = ref<FormInstance>();

// 添加品牌

const addTrademark = async () => {
  await trademarkFormRef.value?.validate();

  const { id, tmName, logoUrl } = trademarkFormDate;

  if (id) {
    await updateTrademarkApi(trademarkFormDate);
  } else {
    await saveTrademarkApi(tmName, logoUrl);
  }

  dialogVisible.value = false;

  ElMessage.success(`${id ? "修改" : "添加"}品牌成功`);
  // 重新获取数据
  getTrademarkList();
};

// 删除品牌
const deleteTrademark = (row: TrademarkModel) => {
  ElMessageBox.confirm(`你确认要删除 ${row.tmName}吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await removeTrademarkApi(row.id);
    ElMessage.success("删除成功");

    getTrademarkList();
  });
};

// 封装复用品牌对话框函数
// 显示添加和修改品牌对话框

const showOrUpdateTrademarkDialog = (row: TrademarkModel) => {
  dialogVisible.value = true;
  trademarkFormDate.tmName = row.tmName;
  trademarkFormDate.logoUrl = row.logoUrl;
  trademarkFormDate.id = row.id;
  trademarkFormRef.value?.clearValidate();
};

// 显示修改品牌对话框
// const showUpdateTrademarkDialog = (row: TrademarkModel) => {
//   dialogVisible.value = true;
//   trademarkFormDate.tmName = row.tmName;
//   trademarkFormDate.logoUrl = row.logoUrl;
//   trademarkFormDate.id = row.id;
//   trademarkFormRef.value?.clearValidate();
// };

// 对话框
const dialogVisible = ref(false);

// 显示添加品牌对话框
// const showTrademarkDialog = () => {
//    dialogVisible.value = true;
//    trademarkFormDate.tmName = "";
//    trademarkFormDate.logoUrl = "";
//    trademarkFormDate.id = 0;
//    trademarkFormRef.value?.clearValidate();
// };

// 文件上传成功触发的回调
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  trademarkFormDate.logoUrl = response.data;

  trademarkFormRef.value?.clearValidate(["logoUrl"]);
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // rawFile.type 文件类型

  const validImageType = ["image/jpeg", "image/jpg", "image/png"];
  if (!validImageType.includes(rawFile.type)) {
    ElMessage.error("图片类型只能是jpeg、jpg或png格式!");
    return false;
  } else if (rawFile.size / 1024 > 200) {
    ElMessage.error("图片大小必须小于200KB!");
    return false;
  }
  return true;
};
</script>

<style scoped lang="scss">
.trademark-table {
  margin: 20px 0;
}
.trademark-pagination :deep() {
  .el-pagination__sizes {
    position: absolute;
    right: 130px;
  }
  .el-pagination__total {
    position: absolute;
    right: 40px;
  }
}

.trademark-img {
  width: 100px;
  height: 100px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
